﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace DSPL.Contracts.DataGridBehaviours
{
    public class KeyBoardFocusExtention
    {
        public static bool GetKeyboardFocusOnFirstRow(DependencyObject obj)
        {
            return (bool)obj.GetValue(KeyboardFocusOnFirstRowProperty);
        }

        public static void SetKeyboardFocusOnFirstRow(DependencyObject obj, bool value)
        {
            obj.SetValue(KeyboardFocusOnFirstRowProperty, value);
        }

        // Using a DependencyProperty as the backing store for KeyboardFocus.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty KeyboardFocusOnFirstRowProperty =
            DependencyProperty.RegisterAttached("KeyboardFocusOnFirstRow", typeof(bool), typeof(DataGrid), new PropertyMetadata(false, OnKeyboardFocusOnFirstRowPropertyChanged));

        private static void OnKeyboardFocusOnFirstRowPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            DataGrid dataGrid = d as DataGrid;

            if (dataGrid != null && (bool)e.NewValue)
            {
                dataGrid.Loaded -= dataGrid_Loaded;
                dataGrid.Loaded += dataGrid_Loaded;
            }
        }

        static void dataGrid_Loaded(object sender, RoutedEventArgs e)
        {           

            DataGrid dataGrid = sender as DataGrid;

            if (DesignerProperties.GetIsInDesignMode(dataGrid))
                return;

            if (dataGrid != null)
            {             

                object item = dataGrid.Items[0];
                dataGrid.SelectedItem = item;

                DataGridRow row = dataGrid.ItemContainerGenerator.ContainerFromIndex(0) as DataGridRow;
                if (row == null)
                {
                    dataGrid.ScrollIntoView(item);
                    row = dataGrid.ItemContainerGenerator.ContainerFromIndex(0) as DataGridRow;
                }

                DataGridCellInfo cellInfo = dataGrid.SelectedCells[0];

                var cellContent = cellInfo.Column.GetCellContent(cellInfo.Item);

                DataGridCell dataGridCell = (DataGridCell)cellContent.Parent;

                Keyboard.Focus(dataGridCell);
            }
        }
    }
}
